package com.google.code.sysarch.v2;

public class SantaHelper extends Thread {
	private static int reindeersAwake = 0;
	private boolean isEating = false;
	private boolean isInHutch = true;
	private int eatingProgress = 0;
	private int workingProgress = 0;
	public int posX = 0;
	public int posY = 0;
	
	/**
	 * initializes the reindeer
	 */
	SantaHelper() {
		/*
		 * when the reindeer is created, it is weak
		 * and needs to eat something
		 * it is in the hutch and knows who Santa is.
		 */
		this.eatingProgress = 0;
		this.isEating = true;
		this.isInHutch = true;
		
		/*
		 * now our reindeer is ready for the real life!
		 * run() get's work for the reindeer
		 */ 
	}

	
	/**
	 * moves imediately to the new position 
	 * @param px
	 * @param py
	 */
	public void moveTo(int px, int py) {
		this.posX = px;
		this.posY = py;
		Main.myGUI.repaint();
		//System.out.println("move to "+posX+"x"+posY);
	}

	
	/**
	 * moves slightly to the new position
	 * @param px
	 * @param py
	 */
	public void slightlyMoveTo(int px, int py) {
		// TODO
	}


	/**
	 * gets new work for the reindeer and calls "leaveHutch()"
	 * @return 
	 */
	public void run() {
		while (true) {
			if (Math.random()*2>=1) this.moveTo((int)(this.posX + Math.random()*20), this.posY);
			if (Math.random()*2>=1) this.moveTo((int)(this.posX - Math.random()*20), this.posY);
			if (Math.random()*2>=1) this.moveTo(this.posX, (int)(this.posY + Math.random()*20));
			if (Math.random()*2>=1) this.moveTo(this.posX, (int)(this.posY - Math.random()*20));
			if (this.isEating) {
				// do some eating here
				eatingProgress++;
				if (eatingProgress == 100) {
					eatingProgress = 0;
					isEating = false;
				}
			}			
		
			// check if reindeer is ready to work by now
			if (!this.isEating) {
				// reindeer isn't occupied with eating and can do some work
				if (this.isInHutch == true) {
					this.leaveHutch();
					this.workingProgress = 0;
					/*
					 * get work
					 */
				} else {
					// reindeer already has work
					// TODO: do some work here
					this.workingProgress++;
					if (this.workingProgress == 100) {
						/*
						 * work is done, so go to the hutch
						 */
						workingProgress = 0;
						this.goToHutch();
					}
				}
			}
		
			// check if enough reindeers are awake to wake up Santa
			if (reindeersAwake >= Main.ELFES_ASKING_CREW) {
				synchronized (Main.MySanta) {
					Main.MySanta.notify();
				}
			}
		} // while
	}

	
	/**
	 * GUI: reindeer goes to its hutch
	 */
	public void goToHutch() {
		// TODO
		reindeersAwake--;
		this.isInHutch = true;
	}
	
	/**
	 * GUI: reindeer leaves its hutch to help santa
	 */
	public void leaveHutch() {
		// TODO
		reindeersAwake++;
		this.isInHutch = false;
	}
	

}
